/*
* 公司：Leita Tech
* 版权信息：雷塔所有
* 任务：
* 描述：
* 作者：李大平
* 日期：2020/06/04
*
*/

#include "model/LTFundModel.h"

#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
#include <QDebug>

#include "model/LTModelDefines.h"

LTFundModel::LTFundModel(QObject *parent) :
    LTListModel({"id", "number", "name", "description", "manager", "link", "update_script",
                "state", "pe", "pe_quantile", "pe_oppotunity", "pe_median", "pe_danger", "ttm",
                "increment", "ave_30day", "market_value",
                "update_time"}, parent)
  ,updater_("http://localhost:8000/fund/funds/")
{
    QObject::connect(&updater_, &LTHttpRequester::finished, [=](QNetworkReply* rpy){
        if(rpy->error() == QNetworkReply::NoError)
        {
            auto response_data = rpy->readAll();
            qDebug() << response_data;
            QJsonDocument json_doc = QJsonDocument::fromJson(response_data);
            if(json_doc.isNull())
            {
                error_string_ = "response json document is null.";
            }
            else
            {
                QJsonObject json_obj = json_doc.object();
                if(!json_obj.contains("code") || json_obj.value("code").toInt(0) != 200)
                {
                    error_string_ = response_data;
                }
                else
                {
                    auto cur_time = QDateTime::currentSecsSinceEpoch();
                    QJsonArray fund_array = json_obj.value("data").toArray();
                    for(int i = 0; i < fund_array.size(); i++)
                    {
                        QJsonObject fund_obj = fund_array.at(i).toObject();
                        int fund_data_index = makeData("id", fund_obj["id"].toInt());
                        Data fund_data = getData(fund_data_index);
                        fund_data["number"] = fund_obj["number"].toString();
                        fund_data["name"] = fund_obj["name"].toString();
                        fund_data["description"] = fund_obj["description"].toString();
                        fund_data["link"] = fund_obj["link"].toString();
                        QJsonObject manager_obj = fund_obj["manager"].toObject();
                        fund_data["manager"] = manager_obj;
                        QJsonObject update_script_obj = fund_obj["update_script"].toObject();
                        fund_data["update_script"] = update_script_obj;
                        QJsonObject state_obj = fund_obj["state"].toObject();
                        fund_data["state"] = state_obj;
                        fund_data["update_time"] = cur_time;
                        setData(fund_data_index,fund_data);
                    }
                    deleteDatas([=](const Data& data){
                       return data.value("update_time", 0) != cur_time;
                    });
                }
            }
        }
        else
        {
            qDebug() << "failed.";
            error_string_ = rpy->errorString();
        }
        is_updating_ = false;
        rpy->deleteLater();
        qDebug() << "finished.";
    });
}

bool LTFundModel::update()
{
    qDebug() << "model update.";
    error_string_.clear();
    if(is_updating_)
        return true;
    is_updating_ = updater_.request();
    if(is_updating_)
        error_string_ = "updater failed to start a request.";
    return is_updating_;
}

QString LTFundModel::getError()
{
    return error_string_;
}
